package lingou.homework.postbar.aspect;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lingou.homework.postbar.controller.tool.LogPrinter;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Aspect
public class DebugAspect {
    @Autowired
    LogPrinter logPrinter;

    @Pointcut("execution (* lingou.homework.postbar.controller.*.* (..))")
    private void pt(){}

    private ObjectMapper objectMapper = new ObjectMapper();

    @Around("pt()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
//        logPrinter.println("In: " + pjp.getSignature());
//        logPrinter.println("    Args: " + Arrays.toString(pjp.getArgs()));
        Object ret = pjp.proceed();
        JsonNode jsonNode = null;
        try {
            jsonNode = objectMapper.valueToTree(ret);
            logPrinter.printlnDepth(1, "Resp: " + jsonNode);
        } catch (IllegalArgumentException e) {
//            logPrinter.println(1, "Resp can not be serialized to json: " + ret.toString());
        }
        return ret;
    }
}
